package com.ww7h.ui.mvvm.v

import android.util.SparseArray
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import com.ww7h.ui.mvvm.vm.BaseViewModel

/**
 * ================================================
 * 描述：
 * 来源：     Android Studio.
 * 项目名：   BigObj
 * 包名：     com.ww7h.common.mvvm
 * 创建时间：  2020/11/3 02:30
 * @author   ww
 * ================================================
 */
class ViewCommon {
    private val useViewDataBindingArray = SparseArray<ViewDataBinding>()

    @Synchronized
    fun <VM : BaseViewModel> getViewModel(
        viewModelStoreOwner: ViewModelStoreOwner,
        tClass: Class<VM>
    ): VM {
        return ViewModelProvider(viewModelStoreOwner).get(tClass)
    }

    @Suppress("UNCHECKED_CAST")
    fun <VDB : ViewDataBinding> getViewDataBinding(
        inflater: LayoutInflater,
        viewGroup: ViewGroup?,
        layoutId: Int
    ): VDB {
        synchronized(useViewDataBindingArray) {
            val vdb : ViewDataBinding= (useViewDataBindingArray[layoutId] ?: DataBindingUtil.inflate(inflater, layoutId, viewGroup, false)).let {
                useViewDataBindingArray.put(layoutId, it)
                it
            }
            return  vdb as VDB
        }
    }

    fun clearUseViewDataBindingArrayCache(layoutId: Int) {
        synchronized(useViewDataBindingArray) {
            if (layoutId == 0) {
                useViewDataBindingArray.clear()
            } else {
                useViewDataBindingArray.remove(layoutId)
            }
        }
    }

}
